package mq

import (
	"fmt"
	"github.com/streadway/amqp"
	"monitor_serve/config"
)

var conn *amqp.Connection
var channel *amqp.Channel

// 初始化
func initChannel() bool {
	//1.判断channel是否创建过了
	if channel != nil {
		return true
	}
	//2.获得rabbitmq的一个连接
	conn, err := amqp.Dial(config.RabbitMQ.RabbitURL)
	if err != nil {
		fmt.Println(err)
		return false
	}
	//3.打开一个channel，用于消息的发布和接收
	channel, err = conn.Channel()
	if err != nil {
		fmt.Println(err)
		return false
	}
	return true
}

// 消息发布
func Publish(exchange, routingKey string, msg []byte) bool {
	//1.判断channel是否正常
	if !initChannel() {
		return false
	}
	fmt.Println("Publish mq:", msg)
	//2.发布消息
	err := channel.Publish(
		exchange,
		routingKey,
		false,
		false,
		amqp.Publishing{
			ContentType: "text/plain",
			Body:        msg,
		},
	)
	if err != nil {
		fmt.Println(err)
		return false
	}
	return true
}
